<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
    <!-- <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="抽奖活动名称" prop="prizeName">
        <el-select
        v-model="queryParams.prizeId"
        filterable
        remote
        reserve-keyword
        placeholder="请输入要选择的活动"
        remote-show-suffix
        :remote-method="remoteMethod"
        :loading="loading1"
        style="width: 240px"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      </el-form-item>
      <el-form-item label="抽奖人ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入抽奖人ID"
          clearable
          class="!w-240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 查询</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form> -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="用户名" align="center" prop="userName" fixed />
      <el-table-column label="用户ID" align="center" prop="userId" fixed />
      <el-table-column label="活动名称" align="center" prop="prizeName" />
      <el-table-column label="活动ID" align="center" prop="prizeId" />
      <el-table-column label="机会来源" align="center" prop="sourceName" />
      <el-table-column label="机会次数" align="center" prop="source" />
      <el-table-column label="总次数" align="center" prop="chanceCount" />
      <el-table-column label="已用次数" align="center" prop="usedCount" />
      <el-table-column label="来源时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" min-width="100">
        <template #default="scope">
          <el-button
            type="danger"
            plain
            @click="openDeleteForm('delete', scope.row.chanceId)"
            v-hasPermi="['raffle:chance:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>

import { queryDetail,deletechance,selelctactivity} from '@/api/raffle/chance'
defineOptions({ name: 'RaffleDeleteForm' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryFormRef = ref() // 搜索的表单
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  prizeId: '',
  userId: ''
})

const deleteFormRef = ref() // 表单 Ref
const options = ref([])
const loading1 = ref(false)

const remoteMethod = async(query: string) => {
  if (query) {
    loading1.value = true
    const res =  await selelctactivity({
      pageNo:1,
      pageSize:100,
      prizeName:query
    })
      loading1.value = false
      options.value = res.list.map((item) => {
        return {label:item.prizeName,value:item.prizeId}
      })
  } else {
    options.value = []
  }
}

/** 查询抽奖活动列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await queryDetail(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 打开弹窗 */
const open = async (type: string, row?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  queryParams.prizeId = row.prizeId
  queryParams.userId = row.userId
   getList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.prizeId=''
  // console.log(queryParams,'queryParams')
  handleQuery()
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const submitForm = async () => {
  // 校验表单
  if (!deleteFormRef) return
  const valid = await deleteFormRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  // try {
  //   const data = formData.value as unknown as PostApi.PostVO
  //   if (formType.value === 'create') {
  //     await PostApi.createPost(data)
  //     message.success(t('common.createSuccess'))
  //   } else {
  //     await PostApi.updatePost(data)
  //     message.success(t('common.updateSuccess'))
  //   }
  //   dialogVisible.value = false
  //   // 发送操作成功的事件
  //   emit('success')
  // } finally {
  //   formLoading.value = false
  // }
}

/** 重置表单 */
const resetForm = () => {
  // formData.value = {
  //   userId: '',
  //   prizeId: '',

  //   chanceCount: ''
  // } as any
  deleteFormRef.value?.resetFields()
}

const openDeleteForm=async(type:string, chanceId?:number)=>{
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deletechance({chanceId})
    message.success(t('删除成功'))
    // 刷新列表
    await getList()
  } catch {}
}
</script>
